import React from 'react';
import {
  Text,
  View,
  FlatList,
  ScrollView,
  TouchableOpacity
} from 'react-native';
import _ from 'lodash';
import Icon from 'react-native-vector-icons/Feather';
import { List } from 'antd-mobile';
import styles from './styles';

const renderItems = ({ item, index, ...other }) => {
  const { title,
    value,
    valueStyle = {},
    onPress,
    icon = null,
    labelWidth = 100
  } = item;
  const Content = ({ nonStyle }) => {
    return (
      <View style={[styles.content, (index === 0 && !nonStyle) && styles.contentFirst]}>
        <View style={icon ? styles.icon : styles.nonIcon}>{icon}</View>
        <Text style={[styles.lable, { width: labelWidth }]}>{title}</Text>
        <Text style={[valueStyle, styles.value, nonStyle && { marginRight: 0 }]}>{value}</Text>
      </View>
    );
  };
  if (_.isFunction(onPress)) {
    return (
      <TouchableOpacity onPress={onPress} style={[styles.content, index === 0 && styles.contentFirst]}>
        <Content nonStyle />
        <View style={styles.rightIcon}>
          <Icon name="chevron-right" color="#999" size={22} />
        </View>
      </TouchableOpacity>
    );
  }
  return <Content />;
};

const ItemSeparatorComponent = () => (
  <View style={{ height: 1, backgroundColor: '#ccc', marginLeft: 40 }} />
);

const Title = ({ title, titleRight }) => {
  if (!title && !titleRight) {
    return null;
  }
  return (
    <View style={styles.title}>
      {title ? <Text style={styles.titleTxt}>{title}</Text> : null}
      {titleRight ? <View style={styles.titleRight}>{titleRight}</View> : null}
    </View>
  );
}

export default props => {
  const { keyPrefix = 'key', data, title, titleRight = null } = props;
  if (!data || _.isEmpty(data)) {
    return null;
  }
  const keyExtractor = (item, index) => `${keyPrefix}_${index}`;
  return (
    <FlatList
      ListHeaderComponent={<Title title={title} titleRight={titleRight} />}
      style={styles.wrap}
      data={data}
      keyExtractor={keyExtractor}
      renderItem={renderItems}
      ItemSeparatorComponent={ItemSeparatorComponent}
    />
  );
};
